import { createHref, normalizeBase } from "./html5";

export const START = "";

//! 此文件创建内存路由

/**
 * 创建内存路由
 * @param {*} base
 * @returns
 */
export function createMemoryHistory(base) {
  let listeners = [];
  let queue = [START];
  let position = 0; // 当前地址栈位置
  base = normalizeBase(base);

  function setLocation(location) {
    position++;
    if (position === queue.length) {
      queue.push(location);
    } else {
      queue.splice(position);
      queue.push(location);
    }
  }

  function triggerListeners(to, from, { direction, delta }) {
    const info = {
      direction,
      delta,
      type: "pop",
    };
    for (const callback of listeners) {
      callback(to, from, info);
    }
  }

  const routerHistory = {
    location: START,
    state: {},
    base,
    createHref: createHref.bind(null, base),
    replace(to) {
      queue.splice(position--, 1);
      setLocation(to);
    },
    push(to) {
      setLocation(to);
    },
    listen(callback) {
      listeners.push(callback);
      return () => {
        const index = listeners.indexOf(callback);
        if (index > -1) listeners.splice(index, 1);
      };
    },
    destroy() {
      listeners = [];
      queue = [START];
      position = 0;
    },
    go(delta, shouldTrigger = true) {
      const from = this.location;
      const direction = delta < 0 ? "back" : "forward";
      position = Math.max(0, Math.min(position + delta, queue.length - 1));
      if (shouldTrigger) {
        triggerListeners(this.location, from, {
          direction,
          delta,
        });
      }
    },
  };

  Object.defineProperty(routerHistory, "location", {
    enumerable: true,
    get: () => queue[position],
  });

  return routerHistory;
}
